<template>
  <div class="container">
    <!-- 顶部搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-wrapper">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item>
            <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable>
              <el-option
                v-for="item in projectOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="queryParams.code"
              placeholder="请输入编号"
              clearable
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button :icon="Refresh" @click="resetQuery">
              重置
            </el-button>
            <el-button type="success" :icon="Plus" @click="handleCreate">
              新增报价单
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="list-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="dataList"
        :height="tableHeight"
        element-loading-text="加载中..."
        element-loading-background="rgba(255, 255, 255, 0.7)"
        style="width: 100%"
        stripe
        border
      >
        <el-table-column type="index" width="60" label="序号" align="center" />
        <el-table-column prop="code" label="编号" min-width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="projectName" label="项目名称" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewDetail(scope.row.id)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 项目选择器对话框 -->
    <ArchiveSelector
      v-model="projectSelectorVisible"
      title="选择项目"
      :search-fields="projectSearchFields"
      :table-columns="projectTableColumns"
      :fetch-data-api="fetchProjectList"
      :multiple="false"
      @confirm="handleProjectSelect"
    />
    
    <!-- 新增报价单对话框 -->
    <el-dialog
      v-model="createQuotationDialog.visible"
      title="新增报价单"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form label-width="100px">
        <el-form-item label="选择项目">
          <el-select 
            v-model="createQuotationDialog.projectId" 
            placeholder="请选择项目" 
            style="width: 100%"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="createQuotationDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmCreateQuotation" :loading="createQuotationDialog.loading">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 报价单对话框 -->
    <el-dialog
      v-model="quotationDialog.visible"
      title="报价单详情"
      width="90%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      v-loading="quotationDialog.loading"
      append-to-body
    >
      <div>
        <div class="quotation-actions">
          <el-button type="primary" :icon="Printer" @click="printQuotation">打印报价单</el-button>
          <el-button type="success" @click="saveQuotation">保存报价单</el-button>
        </div>
        
        <div class="quotation-container" id="quotationContent">
          <div class="budget-header">
            <div class="budget-logo">
              <img :src="logo" alt="公司logo" class="logo-image">
            </div>
            <div class="budget-info">
              <h2>集成项目规划方案设备报价清单</h2>
            </div>
          </div>
          
          <table class="budget-table" border="1" cellspacing="0" cellpadding="0">
            <tr>
              <td colspan="4">总价合计大写：</td>
              <td colspan="4">{{ totalAmountInChinese() }}</td>
            </tr>
            <tr>
              <td colspan="4">总价合计小写：</td>
              <td colspan="4">￥{{ calculateTotal().toLocaleString() }}</td>
            </tr>
            <tr>
              <td>报价单位:</td>
              <td colspan="3">浙江中扬立库技术有限公司</td>
              <td>报价人:</td>
              <td colspan="3">{{ quotationData.date }}</td>
            </tr>
            <tr>
              <td>询价单位:</td>
              <td colspan="3">
                <el-input v-model="quotationData.contactPerson" placeholder="请输入联系人" />
              </td>
              <td>收件人:</td>
              <td colspan="3">
                <el-input v-model="quotationData.contactPhone" placeholder="请输入联系电话" />
              </td>
            </tr>
            <tr>
              <td>交货期:</td>
              <td colspan="3">
                <el-input v-model="quotationData.contactPerson" placeholder="请输入联系人" />
              </td>
              <td>报价日期:</td>
              <td colspan="3">
                <el-input v-model="quotationData.contactPhone" placeholder="请输入联系电话" />
              </td>
            </tr>
       
            <tr>
              <td>项目类型:</td>
              <td colspan="3">
                <el-input v-model="quotationData.contactPerson" placeholder="请输入联系人" />
              </td>
              <td></td>
              <td colspan="3">
              </td>
            </tr>

            <tr>
              <td>项目安装地址:</td>
              <td colspan="3">
                <el-input v-model="quotationData.contactPerson" placeholder="请输入联系人" />
              </td>
              <td>报价有效期:</td>
              <td colspan="3">
                <el-input v-model="quotationData.contactPhone" placeholder="请输入联系电话" />
              </td>
            </tr>

            <tr>
              <td>付款方式:</td>
              <td colspan="7">
                <el-input v-model="quotationData.paymentMethod" placeholder="请输入付款方式" />
              </td>
            </tr>
            <tr>
              <td>特别说明:</td>
              <td colspan="7">
                <el-input v-model="quotationData.paymentMethod" placeholder="请输入付款方式" />
              </td>
            </tr>

            <tr class="yellow-bg">
              <td colspan="8">报价明细表</td>
            </tr>
            
            <!-- 添加物料按钮 -->
            <tr>
              <td colspan="8" style="text-align: right; padding: 10px;">
                <el-button type="primary" size="small" @click="openMaterialSelect">
                  <el-icon><Plus /></el-icon>
                  添加物料
                </el-button>
              </td>
            </tr>
            
            <!-- 头部 -->
            <tr>
              <td>序号</td>
              <td>物品</td>
              <td>型号规格</td>
              <td>数量</td>
              <td>单位</td>
              <td>单价（元/单位）</td>
              <td>总价（元）</td>
              <td>操作</td>
            </tr>
            
            <!-- 按分类分组显示数据 -->
            <template v-for="(categoryGroup, categoryName) in groupedItems" :key="categoryName">
              <!-- 分类标题行 -->
              <tr v-if="categoryName" class="category-row">
                <td colspan="8" class="category-name">{{ categoryName }}</td>
              </tr>
              
              <!-- 分类下的商品项 -->
              <tr v-for="(item, index) in categoryGroup" :key="item.id">
                <td>{{ index + 1 }}</td>
                <td>
                  <el-input v-model="item.name" placeholder="名称" />
                </td>
                <td>
                  <el-input v-model="item.specification" placeholder="规格" />
                </td>
                <td>
                  <el-input-number v-model="item.quantity" :min="1" @change="calculateItemTotal(item)" />
                </td>
                <td>
                  <el-input v-model="item.unit" placeholder="单位" />
                </td>
                <td>
                  <el-input-number v-model="item.unitPrice" :min="0" @change="calculateItemTotal(item)" />
                </td>
                <td>{{ item.totalPrice.toFixed(2) }}</td>
                <td>
                  <el-button type="danger" size="small" @click="removeItem(item.id)">删除</el-button>
                </td>
              </tr>
            </template>
            
            <tr class="total-row">
              <td colspan="6">合计</td>
              <td colspan="2">{{ calculateTotal().toFixed(2) }}</td>
            </tr>
            <tr>
              <td>备注：</td>
              <td colspan="7">
                <div>1. 以上报价根据国家税率涨幅含增值税发票；</div>
                <div>2. 报价有效期：{{ quotationData.validityPeriod }}</div>
                <div>3. 交货周期：{{ quotationData.deliveryDate }}</div>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </el-dialog>
    
    <!-- 物料选择对话框 -->
    <material-dialog
      ref="materialDialogRef"
      :multiple="true"
      @handleMaterialSelectionChange="handleMaterialSelectionChange"
      @confirmMaterialSelect="confirmMaterialSelect"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getHistoricalQuotationListApi, saveStructureQuotationApi ,getQuotationDataByProjectIdApi} from '@/api/historicalQuotation/index'
import type { HistoricalQuotation, HistoricalQuotationQuery } from '@/api/historicalQuotation/type'
import { Search, Refresh, Plus, Printer, Download } from '@element-plus/icons-vue'
import ArchiveSelector from "@/components/common/ArchiveSelector.vue"
import { getSimpleProject, getProjectDocumentApi } from '@/api/project'
import { ProjectDocument } from '@/api/project/type'
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入logo图片
import logo from '@/assets/logo.png'
// 导入物料选择对话框组件
import MaterialDialog from '@/views/baseInfo/material/materialDialog/index.vue'

// 遮罩层
const loading = ref(true)
// 总条数
const total = ref(0)
// 历史报价单表格数据
const dataList = ref<HistoricalQuotation[]>([])
// 表格高度自适应
const tableHeight = ref(0)

// 项目选项
const projectOptions = ref<any[]>([])

// 查询参数
const queryParams = reactive<HistoricalQuotationQuery>({
  page: 1,
  limit: 10,
  projectId: undefined,
  code: undefined
})

// 项目选择器相关
const projectSelectorVisible = ref(false)
const projectSearchFields = [
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '项目名称', prop: 'name', type: 'input' as const }
]
const projectTableColumns = [
  { label: '项目编号', prop: 'code' },
  { label: '项目名称', prop: 'name' },
  { label: '项目状态', prop: 'status' }
]

// 新增报价单对话框
const createQuotationDialog = reactive({
  visible: false,
  projectId: null as number | null,
  loading: false
})

// 报价单对话框
const quotationDialog = reactive({
  visible: false,
  projectId: null as number | null,
  projectName: '',
  loading: false
})

// 报价单数据
const quotationData = reactive({
  title: '集成项目规划方案设备报价清单',
  date: new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-'),
  totalAmount: 0,
  paymentMethod: '预付40%，发货付30%，验收合格付30%',
  validityPeriod: '报价单盖章后1年',
  deliveryDate: '合同签订后3天',
  customerName: '',
  contactPerson: '童春辉',
  contactPhone: '18702172783',
  items: [
    {
      id: 1,
      name: '模块化围挡平台',
      specification: '1200*1000*4（*1500）',
      quantity: 1,
      unit: 'set',
      unitPrice: 0,
      totalPrice: 0,
      remarks: '',
      category: '' // 添加分类字段
    }
  ]
})

// 物料选择相关
const materialDialogRef = ref()
const selectedMaterials = ref<any[]>([])

// 计算属性：按分类分组的项目
const groupedItems = computed(() => {
  const groups: Record<string, any[]> = {}
  
  // 先按分类分组
  quotationData.items.forEach(item => {
    const category = item.category || '未分类'
    if (!groups[category]) {
      groups[category] = []
    }
    groups[category].push(item)
  })
  
  return groups
})

// 路由实例
const router = useRouter()

// 获取项目列表 (为ArchiveSelector组件提供)
const fetchProjectList = () => {
  return getSimpleProject()
}

// 处理项目选择
const handleProjectSelect = (selection: ProjectDocument[]) => {
  if (selection && selection.length > 0) {
    queryParams.projectId = selection[0].id
  }
}

// 获取项目选项
const getProjectOptions = async () => {
  try {
    const res = await getSimpleProject()
    projectOptions.value = res.data || []
  } catch (error) {
    console.error('获取项目列表失败', error)
  }
}

// 查询历史报价单列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getHistoricalQuotationListApi(queryParams)
    dataList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取历史报价单列表失败', error)
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.projectId = undefined
  queryParams.code = undefined
  queryParams.page = 1
  getList()
}

// 查看详情按钮操作
const handleViewDetail = (id: number) => {
  router.push({ path: `/compute/historicalQuotation/detail/${id}` })
}

// 每页数量改变
const handleSizeChange = (size: number) => {
  queryParams.limit = size
  getList()
}

// 页码改变
const handleCurrentChange = (page: number) => {
  queryParams.page = page
  getList()
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 格式化金额为大写
const convertToChinese = (money: number) => {
  if (money === 0) {
    return '零元整'
  }
  
  const fraction = ['角', '分']
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  const head = money < 0 ? '负' : ''
  
  money = Math.abs(money)
  
  let s = ''
  
  for (let i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(money * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
  }
  
  s = s || '整'
  
  money = Math.floor(money)
  
  for (let i = 0; i < unit[0].length && money > 0; i++) {
    let p = ''
    for (let j = 0; j < unit[1].length && money > 0; j++) {
      p = digit[money % 10] + unit[1][j] + p
      money = Math.floor(money / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  
  return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
}

// 计算总金额
const calculateTotal = () => {
  return quotationData.items.reduce((total, item) => total + item.totalPrice, 0)
}

// 计算总额大写
const totalAmountInChinese = () => {
  return convertToChinese(calculateTotal())
}

// 新增报价单方法
const handleCreate = () => {
  // 打开简单的项目选择对话框
  createQuotationDialog.visible = true
  createQuotationDialog.projectId = null
}

// 确认创建报价单
const confirmCreateQuotation = async () => {
  if (!createQuotationDialog.projectId) {
    ElMessage.warning('请先选择项目')
    return
  }
  
  try {
    createQuotationDialog.loading = true
    
    // 根据项目获取表单信息
    const res = await getQuotationDataByProjectIdApi(createQuotationDialog.projectId)
    if (res.code === 200 && res.data) {
      // 设置报价单项目信息
      quotationDialog.projectId = createQuotationDialog.projectId
      quotationDialog.projectName = projectOptions.value.find(p => p.id === createQuotationDialog.projectId)?.name || ''
      
      // 设置报价单数据
      quotationData.customerName = res.data.customerName || ''
      quotationData.contactPerson = res.data.customerContact || '童春辉'
      quotationData.contactPhone = res.data.customerPhone || '18702172783'
      quotationData.date = new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-')
      quotationData.paymentMethod = res.data.paymentMethod || '预付40%，发货付30%，验收合格付30%'
      
      // 清空现有商品项
      quotationData.items = []
      
      // 处理后端返回的分类和商品项
      if (res.data.categories && res.data.categories.length > 0) {
        // 遍历所有分类和商品项，转换为前端需要的格式
        let itemId = 1
        res.data.categories.forEach((category: any) => {
          if (category.items && category.items.length > 0) {
            category.items.forEach((item: any) => {
              quotationData.items.push({
                id: itemId++,
                name: item.name || '',
                specification: item.spec || '',
                quantity: item.quantity || 1,
                unit: item.unit || '',
                unitPrice: item.unitPrice || 0,
                totalPrice: item.totalPrice || 0,
                remarks: '',
                category: category.categoryName || ''
              })
            })
          }
        })
      }
      
      // 如果没有商品项，添加一个默认空项
      if (quotationData.items.length === 0) {
        quotationData.items.push({
          id: 1,
          name: '模块化围挡平台',
          specification: '1200*1000*4（*1500）',
          quantity: 1,
          unit: 'set',
          unitPrice: 0,
          totalPrice: 0,
          remarks: '',
          category: ''
        })
      }
      
      // 关闭创建对话框，打开报价单对话框
      createQuotationDialog.visible = false
      quotationDialog.visible = true
    } else {
      ElMessage.error(res.msg || '获取项目数据失败')
    }
  } catch (error) {
    console.error('创建报价单失败', error)
    ElMessage.error('创建报价单失败')
  } finally {
    createQuotationDialog.loading = false
  }
}

// 打印报价单
const printQuotation = () => {
  try {
    // 获取需要打印的内容
    const contentElement = document.getElementById('quotationContent')
    if (!contentElement) {
      ElMessage.error('获取报价单内容失败')
      return
    }

    // 创建一个新窗口用于打印
    const printWindow = window.open('', '_blank', 'width=800,height=600,scrollbars=yes')
    if (!printWindow) {
      ElMessage.error('无法打开打印窗口，请检查浏览器设置是否阻止弹出窗口')
      return
    }

    // 克隆内容以防止修改原始DOM
    const clonedContent = contentElement.cloneNode(true) as HTMLElement
    
    // 处理克隆的内容
    const processContent = (element: HTMLElement): void => {
      // 处理输入框
      const inputs = element.querySelectorAll('.el-input, .el-input-number')
      inputs.forEach((input: Element) => {
        const inputElement = input.querySelector('input')
        if (inputElement) {
          const span = document.createElement('span')
          span.textContent = inputElement.value || ''
          span.style.display = 'inline-block'
          span.style.minWidth = '40px'
          span.style.textAlign = 'center'
          input.parentNode?.replaceChild(span, input)
        }
      })

      // 移除所有按钮
      const buttons = element.querySelectorAll('button, .el-button')
      buttons.forEach((button: Element) => {
        button.remove()
      })
      
      // 确保所有图片使用绝对路径
      const images = element.querySelectorAll('img')
      images.forEach((img: HTMLImageElement) => {
        if (img.src && !img.src.startsWith('http') && !img.src.startsWith('data:')) {
          img.src = new URL(img.src, window.location.origin).href
        }
      })
    }

    // 处理克隆的内容
    processContent(clonedContent)

    // 准备CSS样式
    const styles = [
      '/* 重置样式 */',
      '* {',
      '  box-sizing: border-box;',
      '  margin: 0;',
      '  padding: 0;',
      '}',
      '',
      'body {',
      '  font-family: SimSun, serif;',
      '  padding: 20px;',
      '  background-color: #fff;',
      '}',
      '',
      '@media print {',
      '  @page {',
      '    size: A4 portrait;',
      '    margin: 1cm;',
      '  }',
      '  ',
      '  body {',
      '    -webkit-print-color-adjust: exact !important;',
      '    print-color-adjust: exact !important;',
      '    color-adjust: exact !important;',
      '  }',
      '  ',
      '  .no-print {',
      '    display: none !important;',
      '  }',
      '}',
      '',
      '/* 容器样式 */',
      '.quotation-container {',
      '  width: 100%;',
      '  max-width: 210mm; /* A4 宽度 */',
      '  margin: 0 auto;',
      '  background-color: #fff;',
      '  padding: 20px;',
      '  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);',
      '}',
      '',
      '/* 头部样式 */',
      '.budget-header {',
      '  display: flex;',
      '  justify-content: space-between;',
      '  align-items: center;',
      '  margin-bottom: 24px;',
      '  padding-bottom: 16px;',
      '  border-bottom: 1px solid #ebeef5;',
      '  position: relative;',
      '  text-align: center;',
      '}',
      '',
      '.budget-logo {',
      '  position: absolute;',
      '  top: 10px;',
      '  right: 10px;',
      '}',
      '',
      '.logo-image {',
      '  max-width: 150px;',
      '  height: auto;',
      '}',
      '',
      '.budget-info {',
      '  text-align: center;',
      '  margin: 0 auto;',
      '  width: 100%;',
      '}',
      '',
      '.budget-info h2 {',
      '  margin: 0;',
      '  font-size: 24px;',
      '  color: #303133;',
      '  font-weight: bold;',
      '}',
      '',
      '/* 表格样式 */',
      'table {',
      '  width: 100%;',
      '  border-collapse: collapse;',
      '  table-layout: fixed;',
      '  margin: 16px 0;',
      '}',
      '',
      'table, th, td {',
      '  border: 1px solid black;',
      '}',
      '',
      'th, td {',
      '  padding: 8px;',
      '  text-align: center;',
      '  vertical-align: middle;',
      '  font-size: 14px;',
      '  word-break: break-word;',
      '}',
      '',
      '/* 特殊行样式 */',
      '.yellow-bg {',
      '  background-color: #FFFF00 !important;',
      '}',
      '',
      '.yellow-bg td {',
      '  text-align: center;',
      '  vertical-align: middle;',
      '  font-weight: bold;',
      '}',
      '',
      '.category-row {',
      '  background-color: #f2f6fc !important;',
      '}',
      '',
      '.category-name {',
      '  font-weight: bold;',
      '  text-align: left;',
      '  padding-left: 20px;',
      '  color: #409EFF;',
      '}',
      '',
      '.total-row td {',
      '  font-weight: bold;',
      '  background-color: #f2f2f2 !important;',
      '}'
    ].join('\n')
    
    // 准备打印内容HTML - 隐藏手动打印按钮
    const bodyContent = [
      '<div class="print-controls no-print">',
      '<button class="print-button" onclick="window.close()">关闭</button>',
      '</div>',
      '<div class="quotation-container">',
      clonedContent.innerHTML,
      '</div>'
    ].join('\n')
    
    // 准备脚本 - 自动触发打印
    const scriptContent = [
      'window.onload = function() {',
      '  // 给图片加载的时间',
      '  setTimeout(function() {',
      '    // 自动打印',
      '    window.print();',
      '  }, 1000);',
      '};'
    ].join('\n')
    
    // 构建HTML内容 - 需要确保正确转义标签
    const htmlContent = [
      '<!DOCTYPE html>',
      '<html>',
      '<head>',
      '<title>报价清单</title>',
      '<meta charset="utf-8">',
      '<style>',
      styles,
      '</style>',
      '</head>',
      '<body>',
      bodyContent,
      '<scr' + 'ipt>',
      scriptContent,
      '</scr' + 'ipt>',
      '</body>',
      '</html>'
    ].join('\n')
    
    // 写入打印窗口 - 一次性写入全部内容
    printWindow.document.write(htmlContent)

    // 完成文档写入并关闭
    printWindow.document.close()
    printWindow.focus()
  } catch (error) {
    console.error('打印报价单失败', error)
    ElMessage.error('打印报价单失败：' + ((error as Error).message || '未知错误'))
  }
}

// 保存报价单
const saveQuotation = async () => {
  if (!quotationDialog.projectId) {
    ElMessage.warning('请先选择项目')
    return
  }
  
  try {
    quotationDialog.loading = true
    
    const contentElement = document.getElementById('quotationContent')
    if (!contentElement) {
      ElMessage.error('获取报价单内容失败')
      return
    }
    
    // 克隆内容以防止修改原始DOM
    const clonedContent = contentElement.cloneNode(true) as HTMLElement
    
    // 处理克隆的内容 - 与打印功能完全相同的处理方式
    const processContent = (element: HTMLElement): void => {
      // 处理输入框
      const inputs = element.querySelectorAll('.el-input, .el-input-number')
      inputs.forEach((input: Element) => {
        const inputElement = input.querySelector('input')
        if (inputElement) {
          const span = document.createElement('span')
          span.textContent = inputElement.value || ''
          span.style.display = 'inline-block'
          span.style.minWidth = '40px'
          span.style.textAlign = 'center'
          input.parentNode?.replaceChild(span, input)
        }
      })

      // 移除所有按钮
      const buttons = element.querySelectorAll('button, .el-button')
      buttons.forEach((button: Element) => {
        button.remove()
      })
      
      // 确保所有图片使用绝对路径
      const images = element.querySelectorAll('img')
      images.forEach((img: HTMLImageElement) => {
        if (img.src && !img.src.startsWith('http') && !img.src.startsWith('data:')) {
          img.src = new URL(img.src, window.location.origin).href
        }
      })
    }

    // 处理克隆的内容
    processContent(clonedContent)
    
    // 准备CSS样式 - 使用与打印功能相同的样式
    const styles = [
      '/* 重置样式 */',
      '* {',
      '  box-sizing: border-box;',
      '  margin: 0;',
      '  padding: 0;',
      '}',
      '',
      'body {',
      '  font-family: SimSun, serif;',
      '  padding: 20px;',
      '  background-color: #fff;',
      '}',
      '',
      '@media print {',
      '  @page {',
      '    size: A4 portrait;',
      '    margin: 1cm;',
      '  }',
      '  ',
      '  body {',
      '    -webkit-print-color-adjust: exact !important;',
      '    print-color-adjust: exact !important;',
      '    color-adjust: exact !important;',
      '  }',
      '}',
      '',
      '/* 容器样式 */',
      '.quotation-container {',
      '  width: 100%;',
      '  max-width: 210mm; /* A4 宽度 */',
      '  margin: 0 auto;',
      '  background-color: #fff;',
      '  padding: 20px;',
      '  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);',
      '}',
      '',
      '/* 头部样式 */',
      '.budget-header {',
      '  display: flex;',
      '  justify-content: space-between;',
      '  align-items: center;',
      '  margin-bottom: 24px;',
      '  padding-bottom: 16px;',
      '  border-bottom: 1px solid #ebeef5;',
      '  position: relative;',
      '  text-align: center;',
      '}',
      '',
      '.budget-logo {',
      '  position: absolute;',
      '  top: 10px;',
      '  right: 10px;',
      '}',
      '',
      '.logo-image {',
      '  max-width: 150px;',
      '  height: auto;',
      '}',
      '',
      '.budget-info {',
      '  text-align: center;',
      '  margin: 0 auto;',
      '  width: 100%;',
      '}',
      '',
      '.budget-info h2 {',
      '  margin: 0;',
      '  font-size: 24px;',
      '  color: #303133;',
      '  font-weight: bold;',
      '}',
      '',
      '/* 表格样式 */',
      'table {',
      '  width: 100%;',
      '  border-collapse: collapse;',
      '  table-layout: fixed;',
      '  margin: 16px 0;',
      '}',
      '',
      'table, th, td {',
      '  border: 1px solid black;',
      '}',
      '',
      'th, td {',
      '  padding: 8px;',
      '  text-align: center;',
      '  vertical-align: middle;',
      '  font-size: 14px;',
      '  word-break: break-word;',
      '}',
      '',
      '/* 特殊行样式 */',
      '.yellow-bg {',
      '  background-color: #FFFF00 !important;',
      '}',
      '',
      '.yellow-bg td {',
      '  text-align: center;',
      '  vertical-align: middle;',
      '  font-weight: bold;',
      '}',
      '',
      '.category-row {',
      '  background-color: #f2f6fc !important;',
      '}',
      '',
      '.category-name {',
      '  font-weight: bold;',
      '  text-align: left;',
      '  padding-left: 20px;',
      '  color: #409EFF;',
      '}',
      '',
      '.total-row td {',
      '  font-weight: bold;',
      '  background-color: #f2f2f2 !important;',
      '}'
    ].join('\n')
    
    // 创建HTML文档内容部分
    const bodyContent = [
      '<div class="quotation-container">',
      clonedContent.innerHTML,
      '</div>'
    ].join('\n')
    
    // 构建HTML内容 - 与打印功能相同的方式
    const htmlContent = [
      '<!DOCTYPE html>',
      '<html>',
      '<head>',
      '<title>报价清单</title>',
      '<meta charset="utf-8">',
      '<style>',
      styles,
      '</style>',
      '</head>',
      '<body>',
      bodyContent,
      '</body>',
      '</html>'
    ].join('\n')
    
    // 构建保存参数
    const params = {
      projectId: quotationDialog.projectId,
      content: htmlContent
    }
    
    // 调用保存接口
    const res = await saveStructureQuotationApi(params)
    
    if (res.code === 200) {
      ElMessage.success('保存成功')
      quotationDialog.visible = false
      getList() // 刷新列表
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存报价单失败', error)
    ElMessage.error('保存报价单失败')
  } finally {
    quotationDialog.loading = false
  }
}

// 删除商品项
const removeItem = (itemId: number) => {
  const index = quotationData.items.findIndex(item => item.id === itemId)
  if (index !== -1) {
    quotationData.items.splice(index, 1)
  }
}

// 计算行项目总价
const calculateItemTotal = (item: any) => {
  item.totalPrice = item.quantity * item.unitPrice
  quotationData.totalAmount = calculateTotal()
}

// 打开物料选择弹框
const openMaterialSelect = () => {
  materialDialogRef.value.onShow(selectedMaterials.value)
}

// 处理物料选择变化
const handleMaterialSelectionChange = (selection: any) => {
  // 更新已选中的物料
  selectedMaterials.value = selection
}

// 确认物料选择
const confirmMaterialSelect = () => {
  if (selectedMaterials.value.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }
  
  // 获取当前最大的ID值
  const maxId = quotationData.items.length > 0 
    ? Math.max(...quotationData.items.map(item => item.id)) 
    : 0
  
  // 将选中的物料添加到报价单项目中
  selectedMaterials.value.forEach((material, index) => {
    // 检查物料是否已存在于报价单中
    const existingItem = quotationData.items.find(item => 
      item.name === material.materialName && 
      item.specification === material.specification
    )
    
    if (!existingItem) {
      // 添加新物料项
      quotationData.items.push({
        id: maxId + index + 1,
        name: material.materialName,
        specification: material.specification || '',
        quantity: 1,
        unit: material.unitName || '个',
        unitPrice: material.purchasePrice || 0,
        totalPrice: material.purchasePrice || 0,
        remarks: '',
        category: material.categoryName || '未分类'
      })
    }
  })
  
  ElMessage.success(`已添加 ${selectedMaterials.value.length} 个物料到报价单`)
  materialDialogRef.value.onClose()
}

onMounted(() => {
  getProjectOptions()
  getList()
  
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    nextTick(() => {
      tableHeight.value = window.innerHeight - 260
    })
  })
})
</script>

<style scoped lang="scss">
.container {
  padding: 20px 20px 0px;

  /*顶部搜索卡片*/
  .search-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 15px 20px;
    }

    /*搜索表单*/
    .search-wrapper {
      .demo-form-inline {
        .el-form-item {
          margin-bottom: 0;
          margin-right: 15px;

          &:last-child {
            margin-right: 0;
          }

          .separator {
            margin: 0 5px;
            color: #909399;
          }
        }

        .el-input,
        .el-select {
          width: 220px;
        }
      }
    }
  }

  /*数据表格卡片*/
  .list-card {
    :deep(.el-card__body) {
      padding: 15px 20px 5px;
    }

    /*表格样式*/
    :deep(.el-table) {
      // 表格内容样式
      .date-value {
        color: #606266;
      }
    }
  }

  // 分页器
  .pagination {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
  }
}

/* 报价单样式 */
.quotation-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  
  @media print {
    display: none;
  }
}

.quotation-container {
  background-color: white;
  padding: 20px;
  border: 1px solid #dcdfe6;
  
  .budget-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;
    position: relative;
    text-align: center;
    
    .budget-logo {
      position: absolute;
      top: 10px;
      right: 10px;
      
      .logo-image {
        max-width: 150px;
        height: auto;
      }
    }
    
    .budget-info {
      text-align: center;
      margin: 0 auto;
      width: 100%;
      
      h2 {
        margin: 0;
        font-size: 24px;
        color: #303133;
      }
    }
  }
  
  .budget-table {
    width: 100%;
    border-collapse: collapse;
    margin: 16px 0;
    
    td {
      padding: 8px;
      border: 1px solid #000;
      text-align: center;
      vertical-align: middle;
    }
    
    .yellow-bg {
      background-color: #FFFF00;
    }
    
    .pink-bg {
      background-color: #FFCCCC;
    }
    
    .blue-bg {
      background-color: #CCFFFF;
    }
    
    .category-row {
      background-color: #f2f6fc;
    }
    
    .category-name {
      font-weight: bold;
      text-align: left;
      padding-left: 20px;
      color: #409EFF;
    }
    
    .total-row {
      font-weight: bold;
    }
    
    .total-row td {
      font-weight: bold;
      background-color: #f2f2f2;
    }
    
    /* 输入框样式 */
    :deep(.el-input__wrapper) {
      box-shadow: none;
      padding: 0;
    }
    
    :deep(.el-input__inner) {
      border: none;
      text-align: center;
      height: 32px;
    }
    
    :deep(.el-input-number__decrease),
    :deep(.el-input-number__increase) {
      display: none;
    }
  }
}

@media print {
  .quotation-actions {
    display: none;
  }
  
  .el-dialog {
    width: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
  }
  
  .el-dialog__header,
  .el-dialog__footer {
    display: none !important;
  }
  
  .el-dialog__body {
    padding: 0 !important;
  }
  
  .quotation-container {
    border: none;
    padding: 0;
  }
}
</style> 